//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package board_dao

import (
	"context"
	"fmt"

	"gitcode.com/eteam/api-server/dao/common"
	"gitcode.com/eteam/proto-gen-go.git/board_draw_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type EdgeKeyDbItem struct {
	FromNodeId string `bson:"fromNodeId"`
	FromHandle string `bson:"fromHandle"`
	ToNodeId   string `bson:"toNodeId"`
	ToHandle   string `bson:"toHandle"`
}

type BasicEdgeInfoDbItem struct {
	EdgeType      board_draw_api.EDGE_TYPE `bson:"edgeType"`
	StrokeWidth   uint32                   `bson:"strokeWidth"`
	Color         string                   `bson:"color"`
	HasStartArrow bool                     `bson:"hasStartArrow"`
	HasEndArrow   bool                     `bson:"hasEndArrow"`
	Label         string                   `bson:"label"`
	LlmLink       bool                     `bson:"llmLink"`
}

type DrawEdgeInfoDbItem struct {
	InfoId     string              `bson:"_id"` //自动生成
	BoardId    string              `bson:"boardId"`
	DrawId     string              `bson:"drawId"`
	EdgeKey    EdgeKeyDbItem       `bson:"edgeKey"`
	BasicInfo  BasicEdgeInfoDbItem `bson:"basicInfo"`
	CreateTime int64               `bson:"createTime"`
	UpdateTime int64               `bson:"updateTime"`
}

func (item *DrawEdgeInfoDbItem) ToDrawEdgeInfo() *board_draw_api.DrawEdgeInfo {
	return &board_draw_api.DrawEdgeInfo{
		EdgeKey: &board_draw_api.EdgeKey{
			FromNodeId: item.EdgeKey.FromNodeId,
			FromHandle: item.EdgeKey.FromHandle,
			ToNodeId:   item.EdgeKey.ToNodeId,
			ToHandle:   item.EdgeKey.ToHandle,
		},
		BasicInfo: &board_draw_api.BasicEdgeInfo{
			EdgeType:      item.BasicInfo.EdgeType,
			StrokeWidth:   item.BasicInfo.StrokeWidth,
			Color:         item.BasicInfo.Color,
			HasStartArrow: item.BasicInfo.HasStartArrow,
			HasEndArrow:   item.BasicInfo.HasEndArrow,
			Label:         item.BasicInfo.Label,
			LlmLink:       item.BasicInfo.LlmLink,
		},
		CreateTime: item.CreateTime,
		UpdateTime: item.UpdateTime,
	}
}

type _EdgeInfoDao struct {
	mc *mongo.Collection
}

func newEdgeInfoDao(db *mongo.Database) (*_EdgeInfoDao, error) {
	mc := db.Collection(common.DB_NS_BOARD + "edge")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"drawId", 1}, {"edgeKey.fromNodeId", 1}},
		},
		{
			Keys: bson.D{{"drawId", 1}, {"edgeKey.toNodeId", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_EdgeInfoDao{mc: mc}, err
}

func (db *_EdgeInfoDao) genInfoId(drawId string, edgeKeyItem *EdgeKeyDbItem) string {
	return fmt.Sprintf("%s:%s:%s:%s:%s", drawId, edgeKeyItem.FromNodeId, edgeKeyItem.FromHandle, edgeKeyItem.ToNodeId, edgeKeyItem.ToHandle)
}

func (db *_EdgeInfoDao) Insert(ctx context.Context, dbItem *DrawEdgeInfoDbItem) error {
	dbItem.InfoId = db.genInfoId(dbItem.DrawId, &dbItem.EdgeKey)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_EdgeInfoDao) Exist(ctx context.Context, boardId, drawId string, edgeKeyItem *EdgeKeyDbItem) (bool, error) {
	infoId := db.genInfoId(drawId, edgeKeyItem)
	count, err := db.mc.CountDocuments(ctx, bson.M{"boardId": boardId, "drawId": drawId, "_id": infoId})
	return count > 0, err
}

func (db *_EdgeInfoDao) Get(ctx context.Context, boardId, drawId string, edgeKeyItem *EdgeKeyDbItem) (*DrawEdgeInfoDbItem, error) {
	retItem := &DrawEdgeInfoDbItem{}
	infoId := db.genInfoId(drawId, edgeKeyItem)
	err := db.mc.FindOne(ctx, bson.M{"boardId": boardId, "drawId": drawId, "_id": infoId}).Decode(retItem)
	return retItem, err
}

func (db *_EdgeInfoDao) Remove(ctx context.Context, boardId, drawId string, edgeKeyItem *EdgeKeyDbItem) error {
	infoId := db.genInfoId(drawId, edgeKeyItem)
	_, err := db.mc.DeleteOne(ctx, bson.M{"boardId": boardId, "drawId": drawId, "_id": infoId})
	return err
}

func (db *_EdgeInfoDao) RemoveByFromNode(ctx context.Context, boardId, drawId, fromNodeId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"boardId": boardId, "drawId": drawId, "edgeKey.fromNodeId": fromNodeId})
	return err
}

func (db *_EdgeInfoDao) RemoveByToNode(ctx context.Context, boardId, drawId, toNodeId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"boardId": boardId, "drawId": drawId, "edgeKey.toNodeId": toNodeId})
	return err
}

func (db *_EdgeInfoDao) RemoveByFromNodeHandle(ctx context.Context, boardId, drawId, fromNodeId string, handleList []string) error {
	if len(handleList) == 0 {
		return nil
	}
	_, err := db.mc.DeleteMany(ctx, bson.M{"boardId": boardId, "drawId": drawId,
		"edgeKey.fromNodeId": fromNodeId, "edgeKey.fromHandle": bson.M{"$in": handleList}})
	return err
}

func (db *_EdgeInfoDao) RemoveByToNodeHandle(ctx context.Context, boardId, drawId, toNodeId string, handleList []string) error {
	if len(handleList) == 0 {
		return nil
	}
	_, err := db.mc.DeleteMany(ctx, bson.M{"boardId": boardId, "drawId": drawId,
		"edgeKey.toNodeId": toNodeId, "edgeKey.toHandle": bson.M{"$in": handleList}})
	return err
}

func (db *_EdgeInfoDao) RemoveByDraw(ctx context.Context, boardId, drawId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"boardId": boardId, "drawId": drawId})
	return err
}

func (db *_EdgeInfoDao) Count(ctx context.Context, boardId, drawId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"boardId": boardId, "drawId": drawId})
	return uint32(count), err
}

func (db *_EdgeInfoDao) List(ctx context.Context, boardId, drawId string) ([]*DrawEdgeInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"boardId": boardId, "drawId": drawId}, options.Find().SetSort(bson.M{"createTime": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*DrawEdgeInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_EdgeInfoDao) UpdateBaisc(ctx context.Context, boardId, drawId string, edgeKeyItem *EdgeKeyDbItem, basicItem *BasicEdgeInfoDbItem, updateTime int64) error {
	infoId := db.genInfoId(drawId, edgeKeyItem)
	_, err := db.mc.UpdateOne(ctx, bson.M{"boardId": boardId, "drawId": drawId, "_id": infoId},
		bson.M{"$set": bson.M{
			"basicInfo":  basicItem,
			"updateTime": updateTime,
		}})
	return err
}
